package xyz.ljcc.ccmt.commons.utils.encode;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * 加密算法
 * @author liucan
 *
 */
public class EncodeUtils {

	/**
	 * MD5(Message Digest algorithm 5，信息摘要算法)
	 * @param str
	 * @return
	 */
	public static String md5(String str) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			return new String(digest.digest(str.getBytes()));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * SHA(Secure Hash Algorithm，安全散列算法)
	 * @param str
	 * @return
	 */
	public static byte[] sha1ToBytes(String str) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			byte[] bts = digest.digest(str.getBytes());
			return bts;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	
	/**
	 * DES/3DES(Digital Signature Algorithm，数字签名)
	 * @param keyStr
	 * @param src
	 * @return
	 */
	public static byte[] encryptMode(String keyStr, byte[] src) {

		try {
			// 生成密钥
			SecretKey deskey = new SecretKeySpec(keyStr.getBytes(), "DESede");
			// 加密
			Cipher c1 = Cipher.getInstance("DESede");
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			return c1.doFinal(src);
		} catch (java.security.NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (java.lang.Exception e3) {
			e3.printStackTrace();
		}
		return null;
	}

	public static byte[] decryptMode(String keyStr, byte[] src) {
		try {
			SecretKey deskey = new SecretKeySpec(keyStr.getBytes(), "DESede");
			// 解密
			Cipher c1 = Cipher.getInstance("DESede");
			c1.init(Cipher.DECRYPT_MODE, deskey);
			return c1.doFinal(src);
		} catch (java.security.NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (java.lang.Exception e3) {
			e3.printStackTrace();
		}
		return null;
	}
}
